<template>
    <div class="jnpf-tree-wrapper" @contextmenu.stop.prevent='contexMenuEvent(undefined)'>
        <el-tree :data="dataSource" ref="treeRef" node-key="nodeId" show-checkbox @check-change="handleCheckChange">
            <template #default="{ node, data }">
                <div class="custom-tree-node" @contextmenu.stop.prevent='contexMenuEvent(node, data)'>
                    <div class="custom-tree-node-content">
                        <div v-if="data.type == 0" class="custom-tree-node-content">
                            <es-icon name="wenjian_weixuanzhong" :size="16" />
                            {{ data.label }}
                        </div>
                        <el-tree-select v-model="data.id" value-key="id" node-key="id" :data="featureWebData"
                            :props="treeProps" :render-after-expand="false" style="width: 100%" size="small"
                            v-if="data.type == 1" />
                    </div>
                    <div>
                        <!-- <a @click.stop="append(data)"> 添加 </a> -->
                    </div>
                </div>
            </template>
        </el-tree>
        <ContextMenuCom :baseItems="menuContent"></ContextMenuCom>
    </div>

</template>

<script>
import { getConfig, getList, getFeatureSelector } from '@/api/jnpf'
import ContextMenuCom from "@/components/commom/ContextMenuCom.vue";
import { ESTextLabel } from "esobjs-xe2-plugin/dist-node/esobjs-xe2-plugin-main";
export default {
    components: {
        ContextMenuCom
    },
    props: {
        sourceTree: {
            type: Array,
            default: []
        },
        xbsjEarthUi: {
            type: Object
        }
    },
    data() {
        return {
            dataSource: this.sourceTree,
            value: '',
            featureWebData: [],
            treeProps: {
                label: 'fullName'
            },
            menuContent: [],
            checkModules: {},
        }
    },
    watch: {
        dataSource: {
            handler: function () {
                this.$emit('updateSource', this.dataSource)
            },
            deep: true,
        }
    },
    created() {
        this.fetchFeatureList()
    },
    methods: {
        // 功能列表
        fetchFeatureList() {
            if (!this.featureWebData.length) {
                getFeatureSelector({ type: 1 }).then(res => {
                    this.featureWebData = res.data.list
                })
            }
        },
        // async getConfig(id) {
        //     await getConfig({
        //         id: id
        //     }).then(res => {
        //         let columnData = JSON.parse(res.data.columnData)
        //         this.checkModules[id].config.columnData = columnData
        //         return columnData
        //     })
        // },
        getList(id) {
            getList(id, {
                "currentPage": 1,
                "pageSize": 20,
                "pageType": "{\"activeType\":\"1\",\"startTime\":\"\",\"endTime\":\"\"}",
                "sort": "desc",
                "sidx": "",
                // "menuId": "480100307225809925",
                "queryJson": ""
            }).then(res => {
                this.checkModules[id].list = res.data.list
                this.checkModules[id].pagination = res.data.pagination
                this.createSceneObject(id)
            })
        },
        append(data, type = 0) {
            let id = 'folder-' + Date.now()
            let nodeId = id
            let lable = '新建文件夹'
            if (type == 1) {
                id = ''
                nodeId = 'module-' + Date.now()
                lable = '新建模块'
            }
            const newChild = { id: id, nodeId: nodeId, label: lable, children: [], type: type }
            if (!data) {
                this.dataSource.push(newChild)
                return
            }

            if (!data.hasOwnProperty('children')) {
                data.children = []
            }
            data.children.push(newChild)
        },
        remove(node, data) {
            const parent = node.parent
            const children = parent.data.children || parent.data
            const index = children.findIndex((d) => d.id === data.id)
            children.splice(index, 1)
        },
        contexMenuEvent(node, data) {

            const baseItems = [
                {
                    text: "添加文件夹",
                    keys: "",
                    func: () => {
                        this.append(data, 0)
                    },
                },
                {
                    text: "添加数据模块",
                    keys: "",
                    func: () => {
                        this.append(data, 1)
                    },
                },
            ];
            if (node) {
                baseItems.push(
                    {
                        text: "删除",
                        keys: "",
                        func: () => {
                            this.remove(node, data)
                        },
                    },
                )
            }
            this.menuContent = baseItems
        },
        handleCheckChange(data, checked, indeterminate) {
            console.log(data, checked, indeterminate)
            let checkNodes = this.$refs.treeRef.getCheckedNodes()

            let checkKeys = []
            // console.log(checkNodes)
            checkNodes.map(node => {
                if (node.type == 1) {//非文件夹类型数据
                    if (!node.id) return
                    checkKeys.push(node.id)//比对哪些模块需要隐藏
                    //没加载,加载数据并显示
                    if (!this.checkModules.hasOwnProperty(node.id)) {
                        this.checkModules[node.id] = {
                            config: {
                                columnData: {}
                            },
                            list: [],
                            pagination: {},
                            sceneObjects: [],
                            show: true
                        }
                        this.getModuleInfo(node.id)
                    } else {
                        //加载过：显示出来
                        this.checkModules[node.id].show = true
                        this.checkModules[node.id].sceneObjects.map(obj => {
                            obj.show = true
                        })

                    }
                }
            })
            //找出需要隐藏的模块
            let oldKeys = Object.keys(this.checkModules)
            oldKeys.forEach(key => {
                if (checkKeys.indexOf(key) == -1) {
                    this.checkModules[key].show = false
                    this.checkModules[key].sceneObjects.map(obj => {
                        obj.show = false
                    })
                }
            })
            console.log('checkModules', this.checkModules)

        },
        async getModuleInfo(id) {
            let configRes = await getConfig({ id: id })
            let columnData = JSON.parse(configRes.data.columnData)
            this.checkModules[id].config.columnData = columnData
            this.getList(id)
        },
        createSceneObject(id) {
            let module = this.checkModules[id]
            let mapOptions = module.config.columnData.mapOptions //地图信息配置
            let markerStyle = module.config.columnData.markerStyle //标注风格
            let list = module.list
            let sceneObjects = []
            list.forEach(element => {
                let position = [...JSON.parse(element[mapOptions.lnglat]), 0]
                let point = this.xbsjEarthUi.createSceneObject('ESGeoDiv')
                point.moduleId = id
                point.position = position
                point.originRatioAndOffset = [0.5, 1, 0, 0]
                let renderHtml =
                    ` 
                    <div class="marker">
                        <div class="markerStyle"  name="markerDom" >
                            <div class="markerStyle-bg" name="markerDom">
                                <div class="markerStyle-circle" name="markerDom" style="background: ${markerStyle.backgroundColor} "></div>
                                <div class="markerStyle-rect" name="markerDom" style="background: ${markerStyle.backgroundColor}  "></div>
                            </div>
                            <div class="markerStyle-icon" name="markerDom" style="color:${markerStyle.textColor}">
                                <i class="${markerStyle.icon}" name="markerDom"></i>
                            </div>
                        </div>
                        <div class="markerStyle-text">${element[mapOptions.title]}</div>
                    </div>
                    `

                point.innerHTML = renderHtml
                sceneObjects.push(point)
            })
            this.checkModules[id].sceneObjects = sceneObjects

        },

    },
}
</script>

<style>
.jnpf-tree-wrapper {
    width: 100%;
    height: 100%;
    overflow: auto;
    overflow-anchor: none;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.custom-tree-node-content {
    flex: 1;
    display: flex;
    align-items: center;
    padding-right: 10px;
}
</style>

<style>
.marker{
    display: flex;
    flex-direction: column;
    position: relative;
}
.markerStyle-text{
    position: absolute;
    top:40px;
    background: rgba(0, 0, 0, .7);
    color:#fff;
    line-height: 1.5em;
    font-size:13px;
    white-space: nowrap;
    left:50%;
    transform: translate(-50%);
    border-radius: 5px;
    padding: 0 5px;
}
.markerStyle {
    width: 32px;
    height: 38px;
    position: relative;
}

.markerStyle-bg {
    background: transparent;
    transform: rotate(45deg);
    width: 32px;
    height: 32px;
}

.markerStyle-icon {
    position: absolute;
    color: #fff;
    position: absolute;
    left: 50%;
    line-height: 30px;
    top: 0;
    transform: translate(-50%);
}

.markerStyle-circle {
    position: absolute;
    left: 0;
    top: 0;
    border-radius: 100%;
    box-sizing: border-box;
    width: 32px;
    height: 32px;
    border: 2px solid rgba(255, 255, 255, 1);
}

.markerStyle-rect {
    position: absolute;
    box-sizing: border-box;
    left: 16px;
    top: 16px;
    width: 16px;
    height: 16px;
    border-bottom: 2px solid rgba(255, 255, 255, 1);
    border-right: 2px solid rgba(255, 255, 255, 1);
}
</style>